<?php defined('SYSPATH') or die('No direct script access.');
/**
 * IVR Controller
 * 
 * PHP version 5
 * LICENSE: This source file is subject to LGPL license 
 * that is available through the world-wide-web at the following URI:
 * http://www.gnu.org/copyleft/lesser.html
 * @author	   Deji Lana <simplydejjy@gmail.com> 
 * @package    IVR
 * @module	   IVR Controller	
 * @copyright  TransformNaija - http://www.transformnaija.net
 * @license    http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License (LGPL) 
* 
*/

class Ivr_Controller extends Controller
{


	
	public function index(){
		
		$download_folder = Kohana::config('ivr.download_folder');
		$handle=opendir($download_folder);

		while (($file = readdir($handle)) != false) {
			//
			
			$file = str_ireplace(".wav", "", $file);
			
			$arr = explode("_", $file);
			
//			print_r($arr);
//			echo '<br>';
//			echo count($arr);
//			echo '<br>';
			
			if(count($arr) < 4)
				continue;
			
			$callerid = $arr[0];
			$lang = $arr[1];
			$category = str_ireplace(".wav", "", $arr[2]);
			$time_stamp = $arr[3];
			
//			echo $category;
			
			$report_wav = Kohana::config('ivr.download_url').$file.".wav";
			
			// Get Report
			$report = $this->_get_sounds($report_wav);
			
			echo $report_wav;
			
			if ($report)
			{
				
				//chekcing if report already exist...
				$exists = ORM::factory('ivr_message')
							->where('time_stamp', $time_stamp)
							->find();
			
				if ($exists->loaded){
					echo 'already exist...';
					continue;
				}
					
					
				echo 'saving report...';
				// Messages Folder Location
				$messages_folder = DOCROOT."media/uploads/ivr/messages/";
				
				// Save Report Sound File Locally
				$fp = fopen($messages_folder.$file.".wav", "w");
				fwrite($fp, $report);
				fclose($fp);
				
				// Now save the details in the database
				$services = ORM::factory('service');
				$service = $services->where('service_name', 'IVR')->find();
				if ( ! $service->loaded) 
					return;
			
				$reporter = ORM::factory('reporter')
					->where('service_id', $service->id)
					->where('service_account', $callerid)
					->find();
				
				// Save CallerID as Reporter
				if (!$reporter->loaded == TRUE)
				{
					// get default reporter level (Untrusted)
					$level = ORM::factory('level')
						->where('level_weight', 0)
						->find();
					
					$reporter->service_id = $service->id;
					$reporter->level_id = $level->id;
					$reporter->service_userid = null;
					$reporter->service_account = $callerid;
					$reporter->reporter_first = null;
					$reporter->reporter_last = null;
					$reporter->reporter_email = null;
					$reporter->reporter_phone = null;
					$reporter->reporter_ip = null;
					$reporter->reporter_date = date('Y-m-d');
					$reporter->save();
				}
				
				// Save Message
				$message = ORM::factory('message');
				$message->reporter_id = $reporter->id;
				$message->message_from = $callerid;
				$message->message_to = null;
				$message->message = "New Voice Message in ".$lang." language at ".date('D, d/m/Y h:i:s');
				$message->message_type = 1; // Inbox
				$message->message_date = date("Y-m-d H:i:s",time());
				$message->service_messageid = null;
				$message->save();
				
				// Save Message to ivr Table
				$ivr = ORM::factory('ivr_message');
				$ivr->message_id = $message->id;
				$ivr->caller_id = $callerid;
				$ivr->language = $lang;
				$ivr->time_stamp = $time_stamp;
				$ivr->category = $category;
				$ivr->message_report = $file.".wav";
				$ivr->save();
			}
			
		}
		closedir($handle);
		
		
	}
	
	private function _get_sounds($url = NULL)
	{
		if ($url)
		{
//			echo $url.'<br/><br/>';
//			$url = Kohana::config('ivr.download_url');
////			$url = "http://localhost/ushahidi/".$url;
			echo $url.'<br/><br/>';
			$curl_handle = curl_init();
			curl_setopt($curl_handle,CURLOPT_URL,$url);
			curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
			curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1); //Set curl to store data in variable instead of print
			$buffer = curl_exec($curl_handle);
			
			/* Check for 404 (file not found). */
			$httpCode = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
			curl_close($curl_handle);
			
			if( $httpCode == 200)
			{
				echo  'got the file';
				return $buffer;
			}
			else
			{
				echo  'no file';
				return false;
			}
		}
		
		
	}
}